package maxinshiSomeipTool20.common.itfSafeSWT;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

/**
 * 通用左右分栏布局组件（确保左侧表格纵向滚动条正常工作）
 */
public class CommonLeftRightPanel {
    // 左侧组件（带滚动）
    private ScrolledComposite leftComposite;
    private Composite leftPanel; 
    private Button addButton;
    private Button delButton;
    private Table dataTable;
    
    // 右侧组件（无滚动）
    private Composite rightComposite;
    private Composite rightPanel;
    
    // 布局比例参数
    private final float leftWidthRatio;
    private final float[] tableColumnRatios;

    /**
     * 构造方法：创建左右分栏布局
     */
    public CommonLeftRightPanel(Composite parent, String[] tableColumnNames, 
                               float leftWidthRatio, float[] tableColumnRatios) {
        // 参数校验（保持不变）
        if (parent == null || parent.isDisposed()) {
            throw new IllegalArgumentException("父容器不能为空或已释放");
        }
        if (tableColumnNames == null || tableColumnNames.length == 0) {
            throw new IllegalArgumentException("表格列名不能为空");
        }
        if (leftWidthRatio <= 0 || leftWidthRatio >= 1) {
            throw new IllegalArgumentException("左侧宽度占比必须在0~1之间");
        }
        if (tableColumnRatios == null || tableColumnRatios.length != tableColumnNames.length) {
            throw new IllegalArgumentException("表格列宽比例数组长度必须与列名数组一致");
        }
        
        float ratioSum = 0;
        for (float ratio : tableColumnRatios) {
            if (ratio <= 0 || ratio >= 1) {
                throw new IllegalArgumentException("表格列宽比例必须在0~1之间");
            }
            ratioSum += ratio;
        }
        if (Math.abs(ratioSum - 1.0f) > 0.01f) {
            throw new IllegalArgumentException("表格列宽比例总和必须为1.0");
        }
        
        this.leftWidthRatio = leftWidthRatio;
        this.tableColumnRatios = tableColumnRatios.clone();

        clearParent(parent);
        
        // 父容器布局设置
        GridLayout parentLayout = new GridLayout(2, false);
        parentLayout.horizontalSpacing = 10;
        parent.setLayout(parentLayout);
        
        // 创建左右面板
        createLeftScrollablePanel(parent, tableColumnNames);
        createRightPanel(parent);
        
        // 窗口大小变化监听
        parent.addControlListener(new ControlAdapter() {
            @Override
            public void controlResized(ControlEvent e) {
                updateColumnWidths(parent);
                updateTableColumnWidths();
            }
        });
        
        updateColumnWidths(parent);
        parent.layout(true, true);
    }

    /**
     * 手动计算并更新左右两列的宽度
     */
    private void updateColumnWidths(Composite parent) {
        if (parent == null || parent.isDisposed()) return;
        
        int parentWidth = parent.getClientArea().width;
        if (parentWidth <= 0) return;
        
        int spacing = ((GridLayout)parent.getLayout()).horizontalSpacing;
        int availableWidth = parentWidth - spacing;
        int leftWidth = (int)(availableWidth * leftWidthRatio);
        int rightWidth = availableWidth - leftWidth;
        
        // 更新左侧宽度
        if (leftComposite != null && !leftComposite.isDisposed()) {
            GridData leftData = (GridData)leftComposite.getLayoutData();
            leftData.widthHint = leftWidth;
            leftComposite.setLayoutData(leftData);
        }
        
        // 更新右侧宽度
        if (rightComposite != null && !rightComposite.isDisposed()) {
            GridData rightData = (GridData)rightComposite.getLayoutData();
            rightData.widthHint = rightWidth;
            rightComposite.setLayoutData(rightData);
        }
        
        updateTableColumnWidths();
    }
    
    /**
     * 根据比例更新表格列宽
     */
    private void updateTableColumnWidths() {
        if (dataTable == null || dataTable.isDisposed() || dataTable.getColumnCount() == 0) {
            return;
        }
        
        int tableWidth = dataTable.getClientArea().width;
        if (tableWidth <= 0 && leftComposite != null && !leftComposite.isDisposed()) {
            tableWidth = leftComposite.getClientArea().width - 20;
        }
        
        TableColumn[] columns = dataTable.getColumns();
        for (int i = 0; i < columns.length && i < tableColumnRatios.length; i++) {
            int columnWidth = (int)(tableWidth * tableColumnRatios[i]);
            columns[i].setWidth(Math.max(50, columnWidth));
        }
    }

    /**
     * 创建左侧带滚动条的面板（重点修复纵向滚动）
     */
    private void createLeftScrollablePanel(Composite parent, String[] tableColumnNames) {
        // 1. 左侧滚动容器：强制启用垂直滚动条，确保数据过多时显示
        leftComposite = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
        leftComposite.setExpandHorizontal(true);
        leftComposite.setExpandVertical(true); // 允许内容垂直扩展（关键）
        
        // 滚动容器布局：垂直方向填满父容器，高度随父容器变化
        GridData scrollGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        leftComposite.setLayoutData(scrollGridData);
        
        // 2. 左侧内容面板：承载按钮和表格
        leftPanel = new Composite(leftComposite, SWT.NONE);
        GridLayout leftLayout = new GridLayout(1, false);
        leftLayout.marginWidth = 5;
        leftLayout.marginHeight = 5;
        leftLayout.verticalSpacing = 5;
        leftPanel.setLayout(leftLayout);
        
        // 按钮区
        Composite buttonPanel = new Composite(leftPanel, SWT.NONE);
        buttonPanel.setLayout(new GridLayout(2, true));
        GridData buttonGridData = new GridData(SWT.FILL, SWT.TOP, true, false);
        buttonPanel.setLayoutData(buttonGridData);
        
        addButton = new Button(buttonPanel, SWT.PUSH);
        addButton.setText("Add");
        addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        // 测试用：添加按钮点击时增加表格数据
        addButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                for (int i = 0; i < 10; i++) {
                    new TableItem(dataTable, SWT.NONE).setText(new String[]{"测试数据" + System.currentTimeMillis(), "测试值" + i});
                }
                updateLeftScrollArea(); // 数据变化后更新滚动区域
            }
        });
        
        delButton = new Button(buttonPanel, SWT.PUSH);
        delButton.setText("Del");
        delButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        delButton.setEnabled(false);
        
        // 3. 表格（核心滚动修复）
        // 表格自身添加垂直滚动条，同时允许外部滚动容器控制
        dataTable = new Table(leftPanel, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE | SWT.V_SCROLL);
        dataTable.setHeaderVisible(true);
        dataTable.setLinesVisible(true);
        
        // 表格布局：垂直方向填充剩余空间，但不限制最大高度（关键）
        GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        // 不设置heightHint，允许表格高度随内容增长
        tableGridData.grabExcessVerticalSpace = true; 
        dataTable.setLayoutData(tableGridData);
        
        // 设置表格列
        setTableHeaders(dataTable, tableColumnNames);
        
        // 表格选择事件
        dataTable.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                delButton.setEnabled(dataTable.getSelectionCount() > 0);
            }
        });
        
        // 表格大小变化时调整列宽
        dataTable.addControlListener(new ControlAdapter() {
            @Override
            public void controlResized(ControlEvent e) {
                updateTableColumnWidths();
            }
        });
        
        // 4. 绑定滚动容器与内容面板，确保内容高度变化时触发滚动
        leftComposite.setContent(leftPanel);
        // 初始大小基于内容计算
        leftPanel.setSize(leftPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT));
        
        // 关键修复：监听内容面板大小变化，实时更新滚动容器
        leftPanel.addControlListener(new ControlAdapter() {
            @Override
            public void controlResized(ControlEvent e) {
                leftComposite.setMinSize(leftPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT));
            }
        });
    }
    
    /**
     * 设置表格列头
     */
    private void setTableHeaders(Table table, String[] columnNames) {
        table.setRedraw(false);
        table.clearAll();
        
        for (int i = 0; i < columnNames.length; i++) {
            TableColumn column = new TableColumn(table, SWT.NONE);
            column.setText(columnNames[i]);
        }
        
        updateTableColumnWidths();
        table.setRedraw(true);
    }

    /**
     * 创建右侧无滚动条的面板
     */
    private void createRightPanel(Composite parent) {
        rightComposite = new Composite(parent, SWT.BORDER);
        rightComposite.setLayout(new GridLayout(1, true));
        
        GridData rightGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
        rightComposite.setLayoutData(rightGridData);
        
        rightPanel = new Composite(rightComposite, SWT.NONE);
        rightPanel.setLayout(new GridLayout(1, true));
        rightPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    }

    /**
     * 更新右侧区域布局
     */
    public void updateRightArea() {
        if (rightPanel != null && !rightPanel.isDisposed()) {
            rightPanel.layout(true, true);
            rightComposite.layout(true, true);
        }
    }

    /**
     * 更新左侧滚动区域（数据变化时必须调用）
     */
    public void updateLeftScrollArea() {
        if (leftPanel != null && !leftPanel.isDisposed()) {
            leftPanel.layout();
            // 关键：重新计算内容大小，确保超出时显示滚动条
            int newHeight = leftPanel.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
            leftPanel.setSize(leftPanel.getSize().x, newHeight);
            leftComposite.setMinSize(leftPanel.getSize());
            updateTableColumnWidths();
        }
    }

    /**
     * 清理父容器中的所有子控件
     */
    private void clearParent(Composite parent) {
        if (parent != null && !parent.isDisposed()) {
            for (Control child : parent.getChildren()) {
                child.dispose();
            }
        }
    }

    // ---------------------- getter方法 ----------------------
    public Button getAddButton() {
        return addButton;
    }

    public Button getDelButton() {
        return delButton;
    }

    public Table getDataTable() {
        return dataTable;
    }

    public Composite getRightPanel() {
        return rightPanel;
    }

    public Composite getLeftPanel() {
        return leftPanel;
    }

    public Composite getLeftComposite() {
        return leftComposite;
    }

    public Composite getRightComposite() {
        return rightComposite;
    }
    
    public float getLeftWidthRatio() {
        return leftWidthRatio;
    }
    
    public float[] getTableColumnRatios() {
        return tableColumnRatios.clone();
    }
}